// pages/main/main.js
import config from '../../config'
import {
    luhnCheck,
    phoneFun
} from '../../utils/util'
const API = config.api
const app = getApp()
Page({
    data: {
        pictures: ['../../images/zfb.jpg'],
        currentIndex: 1,
        interval: null,
        interval2: null,
        sendCodeTimer: null,
        BankType: ['借记卡', '信用卡'],
        BankIndex: '', //默认显示位置
        customItem: '请选择', //为每一列的顶部添加一个自定义的项
        isShowBank: false, // 是否显示银行列表
        sendCodeTime: 0,
        certifBankType: ['身份证', '军官证', '护照(限外籍)', '港澳居民来往内地通行证', '台湾通行证'],
        certifiIndex: '0',
        channel: {
            bankCardName: '',
            bankIdNum: '',
            bankIdtype: '',
            bankCard: '',
            bankMobile: '',
        },
        selectChannel: {
            sign_type: false
        },
        state: 0,
        is_second_account: null,
        agreement: false,
        showTip: false,
        showMask: false,
        isShowTip2: false,
        isShowTip3: false,
        isRead: 0,
        isRead2: 5,
        showimg: false,
        paylist: ['请选择扣款方式', '中国银行信用卡（广东省发行，不包含深圳）', '广发银行'],
        index: 0,
        payvalue: '',
        getBankUrlshow:false,
        applyUrlimg:"",
        orderNo:""
    },       
      //获取用户状态
      getState() {
          let userId = wx.getStorageSync('userId') || '';
        app.http(API.apiGetState, {
            userId: userId
        }).then(res => {
            console.log(res);
            if (res.code == 200) {
                let rspData = JSON.parse(res.rspData);
                console.log(rspData.orderNo);
                this.setData({
                    orderNo:rspData.orderNo
                })
            }
        })
    },
    success_fail() {
        clearInterval(this.data.interval2);
        this.setData({
            interval: null,
            showTip: false,
            showMask: false,
            isShowTip2: false,
        })
    },
    success_fail2() {
        clearInterval(this.data.interval2);
        this.setData({
            interval: null,
            showTip: false,
            showMask: false,
            isShowTip3: false,
        })
    },
    getpayvalue(e) {
        console.log(e);
        this.setData({
            index: e.detail.value,
        })
        this.setData({
            payvalue: this.data.paylist[this.data.index]
        })
        if (this.data.payvalue === '中国银行信用卡(广东省)') {
            this.setData({
                showMask: true,
                isShowTip2: true,
                isRead2: 5,
                interval2: setInterval(() => {
                    if (this.data.isRead2 == 0) {
                        clearInterval(this.data.interval2);
                        this.setData({
                            interval2: null
                        })
                    } else {
                        this.setData({
                            isRead2: this.data.isRead2 - 1
                        })
                    }

                }, 1000)
            })
        }
        if (this.data.payvalue === '广发银行') {
            this.setData({
                showMask: true,
                isShowTip3: true,
                isRead2: 5,
                interval2: setInterval(() => {
                    if (this.data.isRead2 == 0) {
                        clearInterval(this.data.interval2);
                        this.setData({
                            interval2: null
                        })
                    } else {
                        this.setData({
                            isRead2: this.data.isRead2 - 1
                        })
                    }

                }, 1000)
            })
        }
        this.changefn()
    },
    onLoad: function (options) {
        this.getState()
        app.getDeviceSize().then(res => {
            const {
                bottomLift,
                windowHeight
            } = res
            console.log(bottomLift)
            this.setData({
                bottomLift,
                windowHeight
            })
        })

        if (options.etcInfo) {
            let etcInfo = JSON.parse(options.etcInfo)
            this.setData({
                etcInfo,
                ['channel.bankCardName']: etcInfo.saveAccountInfoRequest.organ,
                ['channel.bankIdNum']: etcInfo.saveAccountInfoRequest.idnum,
                ['channel.bankIdtype']: etcInfo.saveAccountInfoRequest.idtype,
            })
        }
    },
    changefn() {
        app.http(API.apiPayChannel, {
            order_id: this.data.etcInfo.order_id,
            product_id: '02',
            vehicle_flag: 0,
            bind_tel: this.data.etcInfo.saveAccountInfoRequest.mobilephone,
        }).then(res => {
            console.log(res)
            if (res.code == 200) {
                let rspData = [];
                let object = JSON.parse(res.rspData).object
                if (Array.isArray(object)) {
                    rspData = object
                } else {
                    rspData = [object]
                }
                let selectChannel = null;
                rspData.forEach((e) => {
                    if ((this.data.payvalue.includes("中国银行") && e.sign_type == 13) || (e.title.includes(this.data.payvalue) && e.sign_type == 73)) {
                        selectChannel = e
                    }

                })
                this.setData({
                    selectChannel: selectChannel,
                })
                // console.log(this.data.selectChannel);
                if (this.data.selectChannel.param1.flag === 1) {
                    this.setData({
                        'channel.bankCard': this.data.selectChannel.param1.bankCard
                    })
                }
                console.log(selectChannel);
                wx.hideLoading();
            } else {
                wx.showToast({
                    title: res.message || '请求超时',
                    icon: 'none',
                    image: '',
                    duration: 3000
                })
            }
        }).catch(err => {
            console.log(err);
            wx.showToast({
                title: '请求超时',
                icon: 'none',
                image: '',
                duration: 3000,
                mask: false
            });

        });
    },
    onpenBank() {
        //打开粤通卡H5
        wx.navigateToMiniProgram({
            appId: 'wxca32cd132ab78a69',
            path: 'pages/H5/H5share?url=https://openapi.boc.cn/appserver/zxkh_single/index.html#/&clientId=873&accChannel=155&appLoading=0&titleBar=0',
            envVersion: 'release',
            success(res) {}
        })
    },
    // onpenBankpay1(){
    //   wx.navigateTo({
    //     url: '/pages/guangfa/guangfa',
    //   })
    // },
    onInput(e) {
        let type = e.target.dataset.type;
        let value = e.detail.value;
        this.setData({
            [type]: value.replace(/\s+/g, "")
        })
    },
    onSendchannelCode() {
        if (this.data.channelCodeLock) return;
        if (!this.data.selectChannel.sign_type) {
            wx.showToast({
                title: '请选择签约银行',
                icon: 'none',
                image: '',
                duration: 3000
            })
            return;
        }
        if (!luhnCheck(this.data.channel.bankCard)) {
            wx.showToast({
                title: '请输入正确的银行卡号',
                icon: 'none',
                image: '',
                duration: 3000
            })
            return;
        }
        if (!phoneFun(this.data.channel.bankMobile)) {
            wx.showToast({
                title: '请输入正确的手机号',
                icon: 'none',
                image: '',
                duration: 3000
            })
            return;
        }

        this.setData({
            channelCodeLock: true
        });
        var parmas = {
            cardChangeFlag: '',
            vehicleType: 0,
            secondAccount: this.data.is_second_account == 1 ? 1 : 0,
            idCardStartTime: this.data.etcInfo.saveAccountInfoRequest.trx_id_stime,
            idCardEndTime: this.data.etcInfo.saveAccountInfoRequest.trx_id_etime,
            idCardAddress: this.data.etcInfo.saveAccountInfoRequest.address,
            idCardPicUrlFront: this.data.etcInfo.saveAccountInfoRequest.idcard_pic_url1,
            idCardPicUrlBack: this.data.etcInfo.saveAccountInfoRequest.idcard_pic_url2,
            funcType: this.data.etcInfo.saveCarInfoRequest.func_type,
            approvedCount: this.data.etcInfo.saveCarInfoRequest.approved_count,
            userId: this.data.userId,
            bindTel: this.data.etcInfo.saveAccountInfoRequest.mobilephone,
            orderId: this.data.etcInfo.order_id,
            signType: this.data.selectChannel.sign_type,
            bankIdtype: this.data.channel.bankIdtype,
            bankIdNum: this.data.channel.bankIdNum,
            bankCardName: this.data.channel.bankCardName,
            bankCard: this.data.channel.bankCard,
            bankMobile: this.data.channel.bankMobile,
            vehiclePlate: this.data.etcInfo.saveCarInfoRequest.vehicle_plate,
            vehicleColor: this.data.etcInfo.saveCarInfoRequest.vehicle_color,
            agentName: this.data.etcInfo.saveCarInfoRequest.owner,
            agentIdNum: this.data.etcInfo.saveCarInfoRequest.owner_id_num,
            agentIdType: this.data.etcInfo.saveCarInfoRequest.owner_id_type == 1 ? 0 : this.data.etcInfo.saveCarInfoRequest.owner_id_type,
        }
        app.http(API.apiBankSigned, parmas).then(res => {
            console.log(res);
            if (res.code != 200) {
                wx.showModal({
                    title: '提示',
                    content: res.message || '发送失败',
                    confirmColor: '#005866',
                    showCancel: false,
                    success(res) {}
                })
                setTimeout(() => {
                    this.setData({
                        channelCodeLock: false
                    })
                }, 2000)

                return
            }
            wx.showToast({
                title: '发送成功',
                icon: 'success',
                duration: 3000,
                mask: false
            });
            let tradeNo = JSON.parse(res.rspData).object
            this.setData({
                sendCodeTime: 60,
                tradeNo: tradeNo.smsCode
            })
            this.data.sendCodeTimer = setInterval(() => {
                this.setData({
                    sendCodeTime: --this.data.sendCodeTime
                })
                if (this.data.sendCodeTime <= 0) {
                    clearInterval(this.data.sendCodeTimer)
                    this.data.sendCodeTime = 0
                    this.setData({
                        channelCodeLock: false,
                        sendCodeTimer: null,
                        sendCodeTime: 0
                    })
                }
            }, 1000)
        }).catch(err => {
            this.setData({
                channelCodeLock: false
            })
            wx.showToast({
                title: '发送验证码失败',
                icon: 'none',
                image: '',
                duration: 3000,
                mask: false
            });
            wx.hideLoading()

        });
    },
    // 绑定银行卡
    bindBank() {
        if (this.data.agreement == false) {
            wx.showToast({
                duration: 1000,
                mask: false,
                title: '先阅读并同意用户服务协议',
                icon: 'none'
            });
            return;
        }
        if (!this.data.selectChannel.sign_type) {
            wx.showToast({
                title: '请选择签约银行',
                icon: 'none',
                image: '',
                duration: 3000
            })
            return;
        }
        if (!luhnCheck(this.data.channel.bankCard)) {
            wx.showToast({
                title: '请输入正确的银行卡号',
                icon: 'none',
                image: '',
                duration: 3000
            })
            return;
        }
        if (!phoneFun(this.data.channel.bankMobile)) {
            wx.showToast({
                title: '请输入正确的手机号',
                icon: 'none',
                image: '',
                duration: 3000
            })
            return;
        }
        if (this.data.channel.verificationCode == '') {
            wx.showToast({
                title: '请输入验证码',
                icon: 'none',
                image: '',
                duration: 3000
            })
            return;
        }
        if (!this.data.tradeNo) {
            wx.showToast({
                title: '请重新获取验证码',
                icon: 'none',
                image: '',
                duration: 3000
            });
            return;
        }
        wx.showLoading({
            title: '提交资料中',
            mask: true,
        });
        app.http(API.apiBankVerify, {
            userId: this.data.userId,
            cardChangeFlag: '',
            marketer: '',
            bindTel: this.data.etcInfo.saveAccountInfoRequest.mobilephone,
            orderId: this.data.etcInfo.order_id,
            bankCardName: this.data.channel.bankCardName,
            bankCard: this.data.channel.bankCard,
            bankMobile: this.data.channel.bankMobile,
            securityCode: this.data.channel.verificationCode,
            signType: this.data.selectChannel.sign_type,
            vehiclePlate: this.data.etcInfo.saveCarInfoRequest.vehicle_plate,
            vehicleColor: this.data.etcInfo.saveCarInfoRequest.vehicle_color,
            smsCode: this.data.tradeNo
        }).then(res => {
            console.log(res);
            if (res.code == 200) {
                wx.redirectTo({
                    url: '/pages/submit_success/submit_success',
                })
                wx.hideLoading();
            } else {
                wx.showModal({
                    title: '提示',
                    content: res.message,
                    confirmColor: '#005866',
                    showCancel: false,
                    success(res) {}
                })
                wx.hideLoading();
            }
        }).catch(err => {
            wx.showToast({
                title: res.message,
                icon: 'none',
                image: '',
                duration: 3000
            });
        })
    },
    toagreement() {
        let url = encodeURIComponent(this.data.selectChannel.sign_protocol);
        wx.navigateTo({
            url: '/pages/outView/outView?url=' + url
        })
    },
    toagreementpay() {
        let url = encodeURIComponent(this.data.selectChannel.sign_protocol);
        wx.navigateTo({
            url: '/pages/outpayView/outpayView?url=' + url
        })
    },
    onpenBankpay() {
        this.setData({
            getBankUrlshow:true
        })
        app.http(API.getBankUrl,{
            orderNo:this.data.orderNo
        }).then(res=>{
            var data = JSON.parse(res.rspData); // 解析 JSON 字符串为 JSON 对象
            var applyUrl = data.apply_url;
            console.log(applyUrl);
            this.setData({
                applyUrlimg:applyUrl
            })
        })
    },
    closebtnfn() {
        this.setData({
            getBankUrlshow:false
        })
    },
    showimgfn() {
        this.setData({
            showimg: true
        })
    },

    previewImage() {
        let userId = wx.getStorageSync('userId');
        app.http(API.bankSigning, {
                signingType: 1,
                userId: userId
            }).then(res => {
                console.log(res);
            }),

            wx.previewImage({
                current: 'http://yxyt.oss-cn-hangzhou.aliyuncs.com/ghac/zfb_qrcode.png', // 当前显示图片的 http 链接
                urls: ['http://yxyt.oss-cn-hangzhou.aliyuncs.com/ghac/zfb_qrcode.png'] // 需要预览的图片 http 链接列表
            })
    },
    previewImage1(){
        wx.previewImage({
            current: 'http://yxyt.oss-cn-hangzhou.aliyuncs.com/ghac/ghac_ysf.png', // 当前显示图片的 http 链接
            urls: ['http://yxyt.oss-cn-hangzhou.aliyuncs.com/ghac/ghac_ysf.png'] // 需要预览的图片 http 链接列表
        })
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },
    onChange(e) {
        this.setData({
            agreement: !this.data.agreement
        })
    },
    onShow() {
        let userId = wx.getStorageSync('userId');
        this.setData({
            userId
        })

    },
    onUnload() {},
    //空函数，解决表单的事件穿透
    checkboxChange() {

    }
})